import inspect
import os

class Convertor(object):
    
    def __init__(self, output_dir):
        self.output_dir = output_dir
        
    def convert(self, file, number, summary, sidebar = None, labels = None):
        self.headers = []
        self.lines = open(file, 'r').readlines()
        
        self.text  = []
        
        in_args = False
        self.current_row    = None
        self.table_type     = None
        self.in_bullet_list = False
        self.bullet_text    = ""
        for line in [line.replace("\n", "") for line in self.lines if line[0] != ";"]:
            """ BULLET LIST """
            if line == "\n" or line == "":
                if self.in_bullet_list:
                    self.text += [self.process_line(self.bullet_text) + "\n"]
                    self.bullet_text = ""
                    self.in_bullet_list = False
                self.text += [""]
            elif line[0:2].upper() == '#B':
                self.bullet_text += "   * "
                text = line.strip().split(" ")                                
                if len(text) > 1:
                    self.bullet_text += "*" + " ".join(text[1:]) + "* "
                self.in_bullet_list = True
            elif self.in_bullet_list:
                self.bullet_text += " " + line.strip()
            elif line[0:2].upper() == '#H':
                self.text += self.add_header(line = line[4:], level = int(line[2]))
            elif line[0:4] in ['<SA>', '<RA>', '<RO>', '<CS>', '<ML>']:
                start_args = True         
                in_args    = True       
                if line[1] == "S":
                    line = "Standard Arguments" 
                    self.table_type = 0
                elif line[1:3] == "RA":
                    line = "Rare/Special Arguments"
                    self.table_type = 1
                elif line[1] == "C":
                    line = "Standard Comparisons"
                    self.table_type = 2
                elif line[1] == "M":
                    line = "Methods"
                    self.table_type = 3
                else:
                    line = "Return Arguments"
                    self.table_type = 4
                    
                self.text += self.add_header(line = line, level = 3)
                #self.text += ['<table border="solid,4px,black" cellpadding="10px">']
                #self.text += ['<tr><td></td><td>_*description*_</td></tr>']
                if self.table_type < 2:
                    self.text += ['|| _*argument*_ || _*description*_ ||']
                elif self.table_type == 2:
                    self.text += ['|| _*comparison*_ || _*example*_ ||']
                elif self.table_type == 3:
                    self.text += ['|| _*method*_ || _*notes*_ ||']
                    
            elif in_args:
                if line[0:5] in ['</SA>', '</RA>', '</RO>', '</CS>']:
                    if self.current_row:
                        self.text += [self.add_row()]
                    in_args    = False
                    self.text += ["\n\n"]
                    self.text += ['<font color="white">____</font>']
                    self.text += ["-------------------------------------------------"]
                    #self.text += ["</table>"]
                elif line[0:5] == "#ROW:":
                    if self.current_row:
                        self.text += [self.add_row()]
                    self.current_row = line[5:].strip()

                elif self.current_row:
                    self.current_row += " " + line                    
                    
            else:
                self.text += [self.process_line(line = line)]
            
            
        self.toc = ["    "]
        self.toc = ["= Overview ="]
        for level,text,link in self.headers:
            if level < 3:
                if level == 1:
                    self.toc.append("   ")
                    pre = "  * "
                else:
                    pre = "    # "
                self.toc += [pre + "[#" + link.replace('`', '') + " " + text.replace('`', '') + "]"]
        self.toc.append("   ")        
        
        self.pragma = []
        if sidebar:
            self.pragma += ["#sidebar " + sidebar]
        if labels:
            self.pragma += ["#labels " + labels]

        self.pragma += ["#summary " + str(number) + ". " + summary]
                
        open(self.output_dir + os.sep + file.replace('docker_', ''), 'w').write("\n".join(self.pragma + self.toc + self.text))
                
    def add_header(self, line, level):
        line   = self.process_line(line = line).strip()
        anchor = line.replace(" ", "_")
        if level == 1:
            header = ["<br/>", "<br/>", "<br/>", "--------", "--------", "<br/>", "<br/>", "<br/>", "= " + line + " ="]
        elif level == 2:
            header = ["<br/>", "=== " + line + " ==="]
        elif level == 3:
            header = ["==== " + line + " ===="]
        elif level == 4:
            header = ["===== " + line + " ====="]
            
        self.headers += [(level, line, anchor)]
        return header
        
    def add_row(self):
        line = self.current_row.split(":")
        cell0 = line[0]
        cell1 = ":".join(line[1:])
        self.current_row = None
        if self.table_type == 2:
            f,b = '', '', #'{{{', '}}}'
        else:
            f,b = '', ''
        line = "|| `" + self.process_line(line = cell0).strip() + "` || " + f + self.process_line(line = cell1).strip() + b + " || "
        return line.replace("\n", "").replace("\t", "").replace("  ", " ").replace("  ", " ").replace("  ", " ").replace("  ", " ")
        
    def process_line(self, line):
        words = line.split(" ") 
        line = ""
        for word in words:
            if word[0:4] == "#PB_":
                word = '<font color="blue">`' + word[4:] + '`</font>'
            elif word[0:4] == "#PG_":
                word = '<font color="green">`' + word[4:] + '`</font>'
            elif word[0:4] == "#PC_":
                word = '`' + word[4:] + '`'
            elif word[0:3] == "#PN":
                word = '<font color="blue">`None`</font>' + word[3:]
            elif word[0:3] == "#PT":
                word = '<font color="blue">`True`</font>' + word[3:]
            elif word[0:3] == "#PF":
                word = '<font color="blue">`False`</font>' + word[3:]
            # Word look up
            if word[0:5] == "#METH":
                word = "'Public' Methods" + word[5:]
            elif word[0:5] == "#ATTR": 
                word = "'Public' Attributes" + word[5:]
            elif word[0:3] == "#SB":
                word = "[http://docs.python.org/library/sqlite3.html Python sqlite3 interface]" + word[3:]

            elif word[0:5] == "#BL: ":
                self.text += ['<br/>']
                word = "  * " + word[5:]

            
            line += word + " " 
            
        return line[0:-1]
    
                
if __name__ == '__main__':
    print os.getcwd()
    convertor = Convertor(output_dir = r'../wiki')

    # api . . . 
    convertor.convert('docker_api_outline.wiki',            number = 'A1',   summary = 'Outline of API documentation',                                sidebar = None,           labels = "Phase-Implementation")
    convertor.convert('docker_api_getting_started.wiki',    number = 'A2',   summary = 'Getting started with pod',                                    sidebar = 'api_outline',  labels = "Phase-Implementation")
    convertor.convert('docker_api_pod_Db.wiki',             number = 'A3',   summary = 'pod.Db database connection',                                  sidebar = 'api_outline',  labels = "Phase-Implementation")
    convertor.convert('docker_api_pod_Meta.wiki',           number = 'A4',   summary = 'pod.Meta metaclass which defines pod.Object class behavior',  sidebar = 'api_outline',  labels = "Phase-Implementation")
    convertor.convert('docker_api_pod_Object.wiki',         number = 'A5',   summary = 'pod.Object parent class for all persistent pod objects',      sidebar = 'api_outline',  labels = "Phase-Implementation")
    convertor.convert('docker_api_pod_query.wiki',          number = 'A6',   summary = 'Querying a pod db and the pod.Query/pod.RawQuery objects',    sidebar = 'api_outline',  labels = "Phase-Implementation")
    convertor.convert('docker_api_pod_collection.wiki',     number = 'A7',   summary = 'pod.List and pod.OrderedDict SQL-based collections ',         sidebar = 'api_outline',  labels = "Phase-Implementation")

    # Discussions . . . 
    convertor.convert('docker_discussion_q_and_a.wiki',                             number = 'D1', summary = 'Questions We Hope Someone Will Ask Us Someday . . .',      sidebar = None, labels = None)
    #convertor.convert('docker_discussion_object_versus_relational_databases.wiki',  number = 'D2', summary = 'object versus relational databases and pod',               sidebar = None, labels = None)
    convertor.convert('docker_discussion_the_pod_speed_trials.wiki',                number = 'D2', summary = 'The pod speed trials',                                     sidebar = None, labels = None)



#summary D1. 


#class WikiMeta(type):
#    
#    def upload(cls, summary = ""):
#        
#        text = "#summary " + getattr(cls, 'summary', "") + "\n"
#        
#        sidebar = getattr(cls, 'sidebar', None)
#        if sidebar:
#            sidebar = sidebar if isinstance(sidebar, str) else sidebar.__name__
#            text += "#sidebar " + sidebar + "\n"
#        
#        #labels = getattr(cls, "labels", None)
#        
#        #print google.upload(file         = "./../" + cls.__name__ + ".wiki", 
#        #                    project_name = settings.project_name, 
#        #                    user_name    = settings.username, 
#        #                    password     = settings.password, 
#        #                    summary      = summary, 
#        #                    labels       = labels)
#        
#        open("./../" + cls.__name__ + ".wiki", 'w').write(text)
#        
#class Wiki(object):
#    __metaclass__ = WikiMeta



